import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {GnOidcConfig} from './OidcConfig';

@Injectable()
export class GnOAuthConfig {

  public static CONFIG_PATH = 'assets/config/oauth.json';

  oidcConfigUri: string;
  clientId: string;
  responseType: string;
  scope: string;
  redirectUri: string;
  oidcConfig: GnOidcConfig;

  private loaded: boolean;

  constructor(private http: HttpClient) {
  }

  load(): Observable<GnOAuthConfig> {
    if (!this.loaded) {
      return new Observable(observer => {
        this.http.get(GnOAuthConfig.CONFIG_PATH)
          .subscribe((resp: GnOAuthConfig) => {
            Object.assign(this, resp);
            this.http.get(this.oidcConfigUri)
              .subscribe((oidcConfig: GnOidcConfig) => {
                this.oidcConfig = oidcConfig;
                this.loaded = true;
                observer.next(this);
              });
          });
      });
    } else {
      return new Observable((observer) => {
        return observer.next(this);
      });
    }
  }

}
